<script setup lang="ts">
import type { OrderSchema } from "@/types/account.types";
import { computed, ref } from "vue";
import { useActiveOrderTable } from "./ActiveOrder";
import { cancelOrder } from "@/api/trade";
import { ElMessage } from "element-plus";

defineOptions({
  name: "active-order"
});

const props = withDefaults(
  defineProps<{
    orders: OrderSchema[];
    height?: string | null;
    size?: "small" | "default" | "large";
    compact?: boolean;
  }>(),
  {
    height: null,
    size: undefined,
    compact: false
  }
);

const { activeOrderColumns, tableSize } = useActiveOrderTable(props.compact);

const activeOrders = computed(() =>
  (props.orders || []).filter(o => o.is_active)
);

// Popover state
const popoverVisible = ref(false);
const selectedOrder = ref<OrderSchema | null>(null);
const isCancelling = ref(false);

const handleRowClick = (row: OrderSchema) => {
  selectedOrder.value = row;
  popoverVisible.value = true;
};

const handleCancel = () => {
  popoverVisible.value = false;
  selectedOrder.value = null;
};

const handleConfirmCancel = async () => {
  if (!selectedOrder.value) return;

  const order = selectedOrder.value;
  isCancelling.value = true;

  try {
    const resp = await cancelOrder(order.trade_app_name, order.vt_order_id);
    if (resp?.success) {
      ElMessage.success("撤单成功");
      popoverVisible.value = false;
      selectedOrder.value = null;
    } else {
      ElMessage.error(`撤单失败: ${resp?.message || "未知错误"}`);
    }
  } catch (e: any) {
    ElMessage.error(`撤单失败: ${e?.message || "网络错误"}`);
  } finally {
    isCancelling.value = false;
  }
};
</script>

<template>
  <div :class="['w-full', props.height ? 'h-full' : '']">
    <pure-table
      row-key="vt_order_id"
      :size="props.size ?? tableSize"
      :data="activeOrders"
      :columns="activeOrderColumns"
      :default-sort="{ prop: 'event_time', order: 'descending' }"
      :height="props.height"
      class="cursor-pointer"
      @row-click="handleRowClick"
    />

    <!-- Popover for order cancellation -->
    <el-dialog
      v-model="popoverVisible"
      title="撤单确认"
      width="500px"
      align-center
    >
      <div v-if="selectedOrder" class="space-y-3">
        <div class="grid grid-cols-2 gap-2 text-sm">
          <div class="text-gray-600">合约:</div>
          <div class="font-medium">{{ selectedOrder.vt_symbol }}</div>

          <div class="text-gray-600">类型:</div>
          <div>{{ selectedOrder.order_type }}</div>

          <div class="text-gray-600">方向:</div>
          <div
            :class="
              selectedOrder.direction === '多'
                ? 'text-text_red_text'
                : 'text-text_green_text'
            "
          >
            {{ selectedOrder.direction }}{{ selectedOrder.offset }}
          </div>

          <div class="text-gray-600">价格:</div>
          <div class="font-medium">{{ selectedOrder.price }}</div>

          <div class="text-gray-600">数量:</div>
          <div>{{ selectedOrder.volume }}</div>

          <div class="text-gray-600">已成交:</div>
          <div>{{ selectedOrder.traded }}</div>

          <div class="text-gray-600">状态:</div>
          <div class="text-[#409EFF]">{{ selectedOrder.status }}</div>

          <div class="text-gray-600">备注:</div>
          <div class="text-xs">{{ selectedOrder.reference || "-" }}</div>

          <div class="text-gray-600">委托号:</div>
          <div class="font-mono text-xs">{{ selectedOrder.vt_order_id }}</div>
        </div>

        <div class="mt-4 rounded bg-yellow-50 p-3 text-sm text-yellow-800">
          <p class="font-medium">是否确认撤单？</p>
        </div>
      </div>

      <template #footer>
        <div class="flex justify-end gap-2">
          <el-button @click="handleCancel">取消</el-button>
          <el-button
            type="danger"
            :loading="isCancelling"
            @click="handleConfirmCancel"
          >
            确认撤单
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.cursor-pointer :deep(.el-table__row) {
  cursor: pointer;
}

.cursor-pointer :deep(.el-table__row:hover) {
  background-color: var(--el-table-row-hover-bg-color);
}
</style>
